package com.taiyi.sqltoy.starter.context.impl;

import com.taiyi.sqltoy.starter.context.UserContext;
import com.taiyi.sqltoy.starter.context.UserInfo;
import org.springframework.stereotype.Component;

/**
 * 基于ThreadLocal的用户上下文实现
 * 
 * @author taiyi
 * @since 1.0.0
 */
@Component("threadLocalUserContext")
public class ThreadLocalUserContext implements UserContext {

    private static final ThreadLocal<UserInfo> USER_CONTEXT = new ThreadLocal<>();

    @Override
    public String getCurrentUserId() {
        UserInfo userInfo = USER_CONTEXT.get();
        return userInfo != null ? userInfo.getUserId() : null;
    }

    @Override
    public String getCurrentUsername() {
        UserInfo userInfo = USER_CONTEXT.get();
        return userInfo != null ? userInfo.getUsername() : null;
    }

    @Override
    public String getCurrentTenantId() {
        UserInfo userInfo = USER_CONTEXT.get();
        return userInfo != null ? userInfo.getTenantId() : null;
    }

    @Override
    public void setCurrentUser(String userId, String username, String tenantId) {
        UserInfo userInfo = new UserInfo(userId, username, tenantId);
        USER_CONTEXT.set(userInfo);
    }

    @Override
    public void clearCurrentUser() {
        USER_CONTEXT.remove();
    }

    /**
     * 获取完整的用户信息
     * 
     * @return 用户信息对象
     */
    public UserInfo getCurrentUserInfo() {
        return USER_CONTEXT.get();
    }

    /**
     * 设置完整的用户信息
     * 
     * @param userInfo 用户信息对象
     */
    public void setCurrentUserInfo(UserInfo userInfo) {
        if (userInfo != null) {
            USER_CONTEXT.set(userInfo);
        } else {
            USER_CONTEXT.remove();
        }
    }
}